package com.wine.exam.controller;

import com.wine.common.annotation.Log;
import com.wine.common.annotation.RepeatSubmit;
import com.wine.common.core.controller.BaseController;
import com.wine.common.core.domain.AjaxResult;
import com.wine.common.enums.BusinessType;
import com.wine.exam.core.controller.BasicController;
import com.wine.exam.domain.Paper;
import com.wine.exam.domain.PaperAnswer;
import com.wine.exam.service.IAnswerService;
import com.wine.exam.service.IPaperAnswerService;
import com.wine.exam.service.IPaperService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Objects;

/**
 * 考试Controller
 *
 * @author wine
 * @date 2022-12-14
 */
@RestController
@RequestMapping("/exam/do")
public class ExamController extends BasicController {
    @Autowired
    private IAnswerService answerService;
    @Autowired
    private IPaperAnswerService paperAnswerService;
    @Autowired
    private IPaperService paperService;

    @RepeatSubmit(interval = 10000, message = "请勿重复提交")
    @PreAuthorize("@ss.hasPermi('exam:paper:doexam')")
    @Log(title = "开始考试", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult doExam(@RequestBody PaperAnswer paperAnswer) {
//        根据前端传来得参数验证是否这张试卷存在
        paperAnswer.setCreateTime(new Date());
        paperAnswer.setExamStartTime(new Date().getTime());
        paperAnswer.setCreateBy(this.getUserId().toString());
        paperAnswer.setUserId(this.getUserId());
        paperAnswer.setTotalScore(0L);
        Paper paper = paperService.getPaper(paperAnswer.getPaperId());
        if (Objects.isNull(paper)) {
            return this.error("试卷错误或者不存在");
        }
        // 分钟，转换成毫秒 注意
        Long suggestTime = paper.getSuggestTime();
        paperAnswer.setExamEndTime(paperAnswer.getExamStartTime() + suggestTime *60 *1000);
        AjaxResult preserve = paperAnswerService.preserve(paperAnswer);
        return preserve;

    }
}
